import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, InputNumber, Select, Switch, message, Space, Tag, Progress, Alert } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined, EyeOutlined } from '@ant-design/icons';
import api from '../api';

const { Option } = Select;

// 字段中文名映射
const fieldLabels = {
  patient_id: '患者ID',
  mrs_90days: '90天mRS评分',
  imaging_exam_number: '影像检查流水号',
  age: '年龄',
  gender: '性别',
  pre_ich_mrs: '脑出血前mRS评分',
  hypertension_history: '高血压病史',
  stroke_history: '卒中病史',
  diabetes_history: '糖尿病史',
  atrial_fibrillation_history: '房颤史',
  coronary_heart_disease_history: '冠心病史',
  smoking_history: '吸烟史',
  alcohol_history: '饮酒史',
  onset_to_imaging_hours: '发病到首次影像检查时间间隔(小时)',
  blood_pressure: '血压值(收缩压/舒张压)',
  ventricular_drainage: '脑室引流',
  hemostatic_treatment: '止血治疗',
  intracranial_pressure_reduction: '降颅压治疗',
  antihypertensive_treatment: '降压治疗',
  sedation_analgesia: '镇静、镇痛治疗',
  antiemetic_gastroprotection: '止吐护胃治疗',
  neurotrophic_treatment: '营养神经治疗',
  hematoma_expansion_event: '血肿扩张事件',
  expansion_probability: '48小时扩张概率',
};

const PatientInfo = () => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [editingId, setEditingId] = useState(null);
  const [search, setSearch] = useState('');
  const [filteredData, setFilteredData] = useState([]);
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10 });
  const [detailVisible, setDetailVisible] = useState(false);
  const [detailRecord, setDetailRecord] = useState(null);

  // 获取患者列表
  const fetchPatients = async () => {
    setLoading(true);
    try {
      const response = await api.get('/patients');
      setData(response.data);
    } catch (error) {
      message.error('获取患者列表失败！');
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchPatients();
  }, []);

  // 搜索和筛选
  useEffect(() => {
    let temp = data;
    if (search) {
      temp = temp.filter(item =>
        (item.patient_id && item.patient_id.includes(search)) ||
        (item.imaging_exam_number && item.imaging_exam_number.includes(search))
      );
    }
    setFilteredData(temp);
  }, [data, search]);
 
  // 处理表单提交
  const handleSubmit = async (values) => {
    try {
      if (editingId) {
        await api.put(`/patients/${editingId}`, values);
        message.success('更新成功！');
      } else {
        await api.post('/patients', values);
        message.success('添加成功！');
      }
      setModalVisible(false);
      form.resetFields();
      fetchPatients();
    } catch (error) {
      message.error('操作失败！');
    }
  };

  // 处理删除
  const handleDelete = async (id) => {
    try {
      await api.delete(`/patients/${id}`);
      message.success('删除成功！');
      fetchPatients();
    } catch (error) {
      message.error('删除失败！');
    }
  };

  // 只显示主要字段
  const columns = [
    { title: '患者ID', dataIndex: 'patient_id', key: 'patient_id' },
    { title: '90天mRS评分', dataIndex: 'mrs_90days', key: 'mrs_90days' },
    { title: '影像检查流水号', dataIndex: 'imaging_exam_number', key: 'imaging_exam_number' },
    { title: '年龄', dataIndex: 'age', key: 'age' },
    { title: '性别', dataIndex: 'gender', key: 'gender' },
    { title: '脑出血前mRS评分', dataIndex: 'pre_ich_mrs', key: 'pre_ich_mrs' },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button
            icon={<EyeOutlined />}
            onClick={() => {
              setDetailRecord(record);
              setDetailVisible(true);
            }}
          >查看</Button>
          <Button type="primary" icon={<EditOutlined />} onClick={() => { setEditingId(record.patient_id); form.setFieldsValue(record); setModalVisible(true); }}>编辑</Button>
          <Button type="primary" danger icon={<DeleteOutlined />} onClick={() => handleDelete(record.patient_id)}>删除</Button>
        </Space>
      ),
    },
  ];

  // 分页、筛选、排序处理
  const handleTableChange = (pag, filters, sorter) => {
    setPagination(pag);
  };

  return (
    <div style={{ padding: 24 }}>
      <Alert
        message="血肿扩张事件：后续检查比首次检查绝对体积（HM_volume）增加≥6 mL或相对体积增加≥33%。48小时扩张概率为AI模型预测值。"
        type="info"
        showIcon
        style={{ marginBottom: 16 }}
      />
      <div style={{ marginBottom: 16, display: 'flex', gap: 8 }}>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => {
            setEditingId(null);
            form.resetFields();
            setModalVisible(true);
          }}
        >
          添加患者
        </Button>
        <Input
          allowClear
          prefix={<SearchOutlined />}
          placeholder="搜索患者ID/影像号"
          style={{ width: 240 }}
          value={search}
          onChange={e => setSearch(e.target.value)}
        />
      </div>

      <Table
        columns={columns}
        dataSource={filteredData}
        loading={loading}
        rowKey="patient_id"
        scroll={{ x: 1200 }}
        pagination={pagination}
        onChange={handleTableChange}
      />

      {/* 详细信息弹窗 */}
      <Modal
        title="患者详细信息"
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={null}
        width={600}
        destroyOnClose
      >
        {detailRecord && (
          <div style={{ display: 'flex', flexWrap: 'wrap' }}>
            {Object.entries(detailRecord).map(([key, value]) => (
              <div key={key} style={{ width: '50%', marginBottom: 8 }}>
                <b>{fieldLabels[key] || key}：</b>
                <span style={{ marginLeft: 4 }}>
                  {typeof value === 'boolean' ? (value ? '是' : '否') :
                    key === 'expansion_probability' && value !== undefined ? <Progress percent={Math.round(value*100)} size="small" status={value>0.5?'exception':'normal'} /> :
                    (value ?? '-')}
                </span>
              </div>
            ))}
          </div>
        )}
      </Modal>

      <Modal
        title={editingId ? '编辑患者信息' : '添加患者信息'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        destroyOnClose
      >
        <Form
          form={form}
          onFinish={handleSubmit}
          layout="vertical"
        >
          <Form.Item name="patient_id" label="患者ID" rules={[{ required: true, message: '请输入患者ID！' }]}> <Input disabled={!!editingId} /> </Form.Item>
          <Form.Item name="mrs_90days" label="90天mRS评分" rules={[{ required: true, message: '请输入90天mRS评分！' }]}> <InputNumber min={0} max={6} style={{ width: '100%' }} /> </Form.Item>
          <Form.Item name="imaging_exam_number" label="影像检查流水号" rules={[{ required: true, message: '请输入14位数字！' }, { pattern: /^\d{14}$/, message: '请输入14位数字！' }]}> <Input /> </Form.Item>
          <Form.Item name="age" label="年龄" rules={[{ required: true, message: '请输入年龄！' }]}> <InputNumber min={0} max={150} style={{ width: '100%' }} /> </Form.Item>
          <Form.Item name="gender" label="性别" rules={[{ required: true, message: '请选择性别！' }]}> <Select> <Option value="男">男</Option> <Option value="女">女</Option> </Select> </Form.Item>
          <Form.Item name="pre_ich_mrs" label="脑出血前mRS评分"> <InputNumber min={0} max={6} style={{ width: '100%' }} /> </Form.Item>
          <Form.Item name="hypertension_history" label="高血压病史" valuePropName="checked"> <Switch checkedChildren="有" unCheckedChildren="无" /> </Form.Item>
          <Form.Item name="stroke_history" label="卒中病史" valuePropName="checked"> <Switch checkedChildren="有" unCheckedChildren="无" /> </Form.Item>
          <Form.Item name="diabetes_history" label="糖尿病史" valuePropName="checked"> <Switch checkedChildren="有" unCheckedChildren="无" /> </Form.Item>
          <Form.Item name="atrial_fibrillation_history" label="房颤史" valuePropName="checked"> <Switch checkedChildren="有" unCheckedChildren="无" /> </Form.Item>
          <Form.Item name="coronary_heart_disease_history" label="冠心病史" valuePropName="checked"> <Switch checkedChildren="有" unCheckedChildren="无" /> </Form.Item>
          <Form.Item name="smoking_history" label="吸烟史" valuePropName="checked"> <Switch checkedChildren="有" unCheckedChildren="无" /> </Form.Item>
          <Form.Item name="alcohol_history" label="饮酒史" valuePropName="checked"> <Switch checkedChildren="有" unCheckedChildren="无" /> </Form.Item>
          <Form.Item name="onset_to_imaging_hours" label="发病到首次影像检查时间间隔(小时)"> <InputNumber min={0} max={1000} step={0.01} style={{ width: '100%' }} /> </Form.Item>
          <Form.Item name="blood_pressure" label="血压值(收缩压/舒张压)"> <Input placeholder="如 120/80" /> </Form.Item>
          <Form.Item name="ventricular_drainage" label="脑室引流" valuePropName="checked"> <Switch checkedChildren="已做" unCheckedChildren="未做" /> </Form.Item>
          <Form.Item name="hemostatic_treatment" label="止血治疗" valuePropName="checked"> <Switch checkedChildren="已做" unCheckedChildren="未做" /> </Form.Item>
          <Form.Item name="intracranial_pressure_reduction" label="降颅压治疗" valuePropName="checked"> <Switch checkedChildren="已做" unCheckedChildren="未做" /> </Form.Item>
          <Form.Item name="antihypertensive_treatment" label="降压治疗" valuePropName="checked"> <Switch checkedChildren="已做" unCheckedChildren="未做" /> </Form.Item>
          <Form.Item name="sedation_analgesia" label="镇静、镇痛治疗" valuePropName="checked"> <Switch checkedChildren="已做" unCheckedChildren="未做" /> </Form.Item>
          <Form.Item name="antiemetic_gastroprotection" label="止吐护胃治疗" valuePropName="checked"> <Switch checkedChildren="已做" unCheckedChildren="未做" /> </Form.Item>
          <Form.Item name="neurotrophic_treatment" label="营养神经治疗" valuePropName="checked"> <Switch checkedChildren="已做" unCheckedChildren="未做" /> </Form.Item>
          <Form.Item> <Button type="primary" htmlType="submit" block>提交</Button> </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default PatientInfo; 